package rest.o.gram.tasks;

import android.os.AsyncTask;
import android.util.Log;
import rest.o.gram.BuildConfig;
import rest.o.gram.RestogramService;
import rest.o.gram.RestogramVenue;
import org.json.rpc.client.HttpJsonRpcClientTransport;
import org.json.rpc.client.JsonRpcInvoker;

/**
 * Created with IntelliJ IDEA.
 * User: Roi
 * Date: 14/04/13
 */
public class GetInfoTask extends AsyncTask<String, Void, RestogramVenue> {
    public GetInfoTask(HttpJsonRpcClientTransport transport, ITaskObserver observer) {
        this.transport = transport;
        this.observer = observer;
    }

    @Override
    protected RestogramVenue doInBackground(String... params) {
        String venueID = params[0];

        JsonRpcInvoker invoker = new JsonRpcInvoker();
        RestogramService service = invoker.get(transport, "restogram", RestogramService.class);

        if (BuildConfig.DEBUG)
            Log.d("REST-O-GRAM", "GET INFO - venue:" + venueID);
        return safeGetInfo(service, venueID);
    }

    @Override
    protected void onPostExecute(RestogramVenue result) {
        observer.onFinished(result);
    }

    private RestogramVenue safeGetInfo(RestogramService service, String venueID) {
        try
        {
            return service.getInfo(venueID);
        }
        catch (Exception e)
        {
            Log.e("REST-O-GRAM", "GET INFO - FIRST ATTEMPT FAILED");
            e.printStackTrace();
            return service.getInfo(venueID);
        }
    }

    private HttpJsonRpcClientTransport transport;
    private ITaskObserver observer;
}
